import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, SafeAreaView, ActivityIndicator, Image, TouchableOpacity, Modal, Dimensions, Switch, ScrollView, Alert, TextInput } from 'react-native';
import Header from '../../../../components/Header';
import { getDeviceMaintainDetailApi, execDeviceMaintainApi, getMaterialListPageApi, getDeviceMaintainRecordApi, confirmMaintainPlanApi } from './api';
import { launchCamera, launchImageLibrary, ImagePickerResponse } from 'react-native-image-picker';
import { PermissionsAndroid, Platform } from 'react-native';
import { Toast } from '@ant-design/react-native';
import xiangjiIcon from '../../../../assets/xiangji.png';
import xIcon from '../../../../assets/x.png';
import jiahaoIcon from '../../../../assets/jiahao.png';
import jianhaoIcon from '../../../../assets/jianhao.png';

interface DeviceMaintainDetailProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
    onNavigateToScreen?: (route: string) => void;
}

const MAINTAIN_STATE_MAP: { [key: number]: string } = {
    1: '待保养',
    2: '保养中',
    3: '已完成',
    4: '已逾期',
};

const DeviceMaintainDetail: React.FC<DeviceMaintainDetailProps> = ({ onNavigateToLogin, onBackPress, onNavigateToScreen }) => {
    const [loading, setLoading] = useState(true);
    const [detailData, setDetailData] = useState<any>(null);
    const [imageModalVisible, setImageModalVisible] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string>('');
    const [maintainStates, setMaintainStates] = useState<{ [key: string]: boolean }>({});
    const [uploadedImages, setUploadedImages] = useState<string[]>([]);

    // 备品备件模态框状态
    const [sparePartsModalVisible, setSparePartsModalVisible] = useState(false);
    const [materialList, setMaterialList] = useState<any>([]);
    const [searchKeyword, setSearchKeyword] = useState('');
    const [materialLoading, setMaterialLoading] = useState(false);

    // 已选择的备品备件
    const [selectedSpareParts, setSelectedSpareParts] = useState<any[]>([]);

    // 复核模态框相关
    const [confirmModalVisible, setConfirmModalVisible] = useState(false);
    const [confirmRemark, setConfirmRemark] = useState('');

    useEffect(() => {
        const planId = (global as any).maintainDetailPlanId;
        if (planId) {
            loadMaintainDetail(planId);
        } else {
            setLoading(false);
        }
    }, []);

    const loadMaintainDetail = async (planId: string) => {
        try {
            setLoading(true);
            let result;
            let planData;
            // 先用原接口获取plan信息，判断state
            const baseResult = await getDeviceMaintainDetailApi(planId);
            planData = baseResult?.data?.plan;
            const state = planData?.state;
            if (state === 2 || state === 3) {
                // 待复核或已复核，调用新接口
                const deviceId = planData?.device_id;
                const cycleId = planData?.cycle_id;
                if (deviceId && planId && cycleId) {
                    result = await getDeviceMaintainRecordApi(deviceId, planId, cycleId);
                } else {
                    result = baseResult;
                }
            } else {
                // 其它状态用原接口
                result = baseResult;
            }
            setDetailData(result?.data || null);
            // 初始化保养项状态（统一用maintain_list）
            if (result?.data?.maintain_list) {
                const initialStates: { [key: string]: boolean } = {};
                result.data.maintain_list.forEach((category: any) => {
                    category.children?.forEach((item: any) => {
                        initialStates[item.id] = !item.normal;
                    });
                });
                setMaintainStates(initialStates);
            }
            // 初始化备品备件
            if (result?.data?.product_list) {
                setSelectedSpareParts(result.data.product_list.map((item: any) => ({
                    ...item,
                    quantity: item.quantity || 0
                })));
            }
        } catch (error) {
            setDetailData(null);
        } finally {
            setLoading(false);
        }
    };

    const handleToggleChange = (itemId: string, value: boolean) => {
        setMaintainStates(prev => ({
            ...prev,
            [itemId]: value
        }));
    };

    const requestCameraPermission = async () => {
        if (Platform.OS === 'android') {
            try {
                const granted = await PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.CAMERA,
                    {
                        title: '相机权限',
                        message: '应用需要访问您的相机来拍摄照片',
                        buttonNeutral: '稍后询问',
                        buttonNegative: '取消',
                        buttonPositive: '确定',
                    }
                );
                return granted === PermissionsAndroid.RESULTS.GRANTED;
            } catch (err) {
                return false;
            }
        }
        return true;
    };

    const handleImageUpload = async () => {
        const hasPermission = await requestCameraPermission();
        if (!hasPermission) return;
        const options = {
            mediaType: 'photo' as const,
            includeBase64: false,
            maxHeight: 2000,
            maxWidth: 2000,
        };
        Alert.alert(
            '选择图片来源',
            '请选择图片来源',
            [
                { text: '取消', style: 'cancel' },
                { text: '拍照', onPress: () => launchCamera(options, handleImageResponse) },
                { text: '从相册选择', onPress: () => launchImageLibrary(options, handleImageResponse) },
            ]
        );
    };

    const handleImageResponse = (response: ImagePickerResponse) => {
        if (response.didCancel) return;
        if (response.errorCode) return;
        if (response.assets && response.assets[0]) {
            const imageUri = response.assets[0].uri;
            if (imageUri) setUploadedImages(prev => [...prev, imageUri]);
        }
    };

    // 保存/复核时组装record_list（统一用maintain_list）
    const handleSave = async () => {
        try {
            const recordList: any[] = [];
            if (detailData?.maintain_list) {
                detailData.maintain_list.forEach((category: any) => {
                    category.children?.forEach((item: any) => {
                        recordList.push({
                            check_id: item.check_id,
                            normal: !maintainStates[item.id]
                        });
                    });
                });
            }
            const picList = uploadedImages.map(imageUri => ({
                link: imageUri,
                file_name: '',
                file_type: '',
                sha1: '',
                file_size: 0
            }));
            // 处理备品备件数据
            const productList = selectedSpareParts
                .filter(item => item.quantity > 0)
                .map(item => ({
                    product_id: item.id,
                    shelf_num: '',
                    quantity: item.quantity
                }));
            const requestData = {
                plan: {
                    id: detailData?.plan?.id,
                    plan_id: detailData?.plan?.id,
                    plan_num: detailData?.plan?.plan_num,
                    cycle_id: detailData?.plan?.cycle_id
                },
                device: {
                    id: detailData?.plan?.device_id
                },
                record_list: recordList,
                pic_list: picList,
                product_list: productList
            };
            console.log('保存请求数据:', requestData);
            await execDeviceMaintainApi(requestData);
            Toast.success('保养任务保存成功');
            setTimeout(() => {
                if (onBackPress) onBackPress();
            }, 500);
        } catch (error) {
            Toast.fail('保存失败，请重试');
        }
    };

    const handleAddSpareParts = async () => {
        setSparePartsModalVisible(true);
        await loadMaterialList();
    };

    const loadMaterialList = async (keyword?: string) => {
        try {
            setMaterialLoading(true);
            const requestData = {
                current: 1,
                size: 10,
                keyword: keyword || ''
            };
            console.log('备品备件接口请求参数:', requestData);

            const response = await getMaterialListPageApi(requestData);
            console.log('备品备件接口返回数据:', response);

            if (response?.data?.records) {
                setMaterialList(response.data.records);
            } else {
                setMaterialList([]);
            }
        } catch (error) {
            console.error('获取备品备件列表失败:', error);
            setMaterialList([]);
        } finally {
            setMaterialLoading(false);
        }
    };

    const handleSearchMaterial = () => {
        loadMaterialList(searchKeyword);
    };

    const handleSearchInputChange = (text: string) => {
        setSearchKeyword(text);
        // 输入后自动触发搜索
        if (text.trim()) {
            loadMaterialList(text.trim());
        } else {
            loadMaterialList('');
        }
    };

    const handleSelectSparePart = (item: any) => {
        // 检查是否已经选择过这个备品备件
        const existingIndex = selectedSpareParts.findIndex(part => part.id === item.id);
        if (existingIndex === -1) {
            // 添加新的备品备件，初始数量为0
            setSelectedSpareParts(prev => [...prev, { ...item, quantity: 0 }]);
        }
        // 关闭模态框
        setSparePartsModalVisible(false);
        setSearchKeyword('');
    };

    const handleQuantityChange = (itemId: string, change: number) => {
        setSelectedSpareParts(prev => prev.map(item => {
            if (item.id === itemId) {
                const newQuantity = Math.max(0, item.quantity + change);
                return { ...item, quantity: newQuantity };
            }
            return item;
        }));
    };

    const handleRemoveSparePart = (itemId: string) => {
        setSelectedSpareParts(prev => prev.filter(item => item.id !== itemId));
    };

    // 复核提交
    const handleConfirm = async () => {
        if (!confirmRemark.trim()) {
            Toast.fail('请输入复核备注');
            return;
        }
        try {
            const planId = detailData?.plan?.id;
            if (!planId) {
                Toast.fail('缺少计划ID');
                return;
            }
            const response = await confirmMaintainPlanApi(planId, confirmRemark.trim());
            if (response?.code === 0) {
                Toast.fail(response?.msg || '复核失败');
                return;
            }
            Toast.success(response?.msg || '复核成功');
            setConfirmModalVisible(false);
            setConfirmRemark('');
            setTimeout(() => {
                if (onBackPress) onBackPress();
            }, 500);
        } catch (error: any) {
            Toast.fail(error?.message || '复核失败，请重试');
        }
    };

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="保养任务详情"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />

            {loading ? (
                <View style={styles.loadingContainer}>
                    <ActivityIndicator size="large" color="#0076ff" />
                    <Text style={styles.loadingText}>加载中...</Text>
                </View>
            ) : (
                <ScrollView contentContainerStyle={styles.content}>
                    {detailData && detailData.plan && (
                        <>
                            <View style={styles.card}>
                                <View style={styles.cardHeader}>
                                    <View style={styles.deviceInfo}>
                                        {detailData.plan.device_link ? (
                                            <TouchableOpacity
                                                style={styles.imageContainer}
                                                onPress={() => {
                                                    setSelectedImage(String(detailData.plan.device_link));
                                                    setImageModalVisible(true);
                                                }}
                                            >
                                                <Image
                                                    source={{ uri: String(detailData.plan.device_link) }}
                                                    style={styles.deviceImg}
                                                    resizeMode="contain"
                                                    onError={e => console.log('图片加载失败')}
                                                />
                                            </TouchableOpacity>
                                        ) : (
                                            <View style={styles.deviceImg} />
                                        )}
                                        <Text style={styles.deviceNum}>{detailData.plan.device_num}</Text>
                                    </View>
                                    <View style={styles.statusButton}>
                                        <Text style={styles.statusText}>{MAINTAIN_STATE_MAP[detailData.plan.state] || '未知'}</Text>
                                    </View>
                                </View>
                                <View style={styles.cardDetails}>
                                    <View style={styles.detailRowGroup}>
                                        <View style={styles.detailItemVertical}>
                                            <Text style={styles.detailLabel}>计划时间</Text>
                                            <Text style={styles.detailValue}>{detailData.plan.plan_day || '无'}</Text>
                                        </View>
                                        <View style={styles.detailItemVertical1}>
                                            <Text style={styles.detailLabel}>计划类型</Text>
                                            <Text style={styles.detailValue}>
                                                {detailData.plan.cycle_type === 1 ? '日' :
                                                    detailData.plan.cycle_type === 2 ? '周' :
                                                        detailData.plan.cycle_type === 3 ? '月' :
                                                            detailData.plan.cycle_type === 4 ? '年' : '未知'}
                                            </Text>
                                        </View>
                                    </View>
                                </View>
                                <View style={styles.planNumberContainer}>
                                    <Text style={styles.detailLabel}>计划单号</Text>
                                    <Text style={styles.detailValue}>{detailData.plan.plan_num || '无'}</Text>
                                </View>
                            </View>

                            {/* 保养项卡片 */}
                            <View style={styles.spotItemCard}>
                                <View style={styles.spotItemLeft}>
                                    <Text style={styles.spotItemText}>保养项（默认正常）</Text>
                                    <Text style={styles.requiredMark}>*</Text>
                                </View>
                                <View style={styles.spotItemRight}>
                                    <Text style={styles.spotItemStatus}>是否正常</Text>
                                </View>
                            </View>

                            {/* 检查项渲染，统一用maintain_list */}
                            {detailData.maintain_list && detailData.maintain_list.length > 0 && (
                                detailData.maintain_list.map((category: any) => (
                                    <View key={category.id} style={styles.checkCategoryCard}>
                                        <Text style={styles.checkCategoryTitle}>{category.check_name}</Text>
                                        {category.children && category.children.map((item: any) => (
                                            <View key={item.id} style={styles.checkItemRow}>
                                                <Text style={styles.checkItemName}>{item.check_name}</Text>
                                                <Switch
                                                    value={!maintainStates[item.id]}
                                                    onValueChange={(value) => handleToggleChange(item.id, !value)}
                                                    trackColor={{ false: '#767577', true: '#81b0ff' }}
                                                    thumbColor={!maintainStates[item.id] ? '#f5dd4b' : '#f4f3f4'}
                                                    ios_backgroundColor="#3e3e3e"
                                                    disabled={detailData.plan.state === 3} // 已复核不可编辑
                                                />
                                            </View>
                                        ))}
                                    </View>
                                ))
                            )}


                            {/* 上传图片卡片 */}
                            <View style={styles.uploadCard}>
                                <Text style={styles.uploadTitle}>上传图片</Text>

                                <View style={styles.imagesRow}>
                                    {/* 显示接口返回的图片 */}
                                    {detailData.pic_list && detailData.pic_list.map((pic: any, index: number) => (
                                        <View key={`server-${index}`} style={styles.imageItem}>
                                            <TouchableOpacity
                                                onPress={() => {
                                                    setSelectedImage(pic.link);
                                                    setImageModalVisible(true);
                                                }}
                                            >
                                                <Image source={{ uri: pic.link }} style={styles.uploadedImage} />
                                            </TouchableOpacity>
                                        </View>
                                    ))}
                                    {/* 显示新上传的图片 */}
                                    {uploadedImages.map((imageUri, index) => (
                                        <View key={`new-${index}`} style={styles.imageItem}>
                                            <TouchableOpacity
                                                onPress={() => {
                                                    setSelectedImage(imageUri);
                                                    setImageModalVisible(true);
                                                }}
                                            >
                                                <Image source={{ uri: imageUri }} style={styles.uploadedImage} />
                                            </TouchableOpacity>
                                            <TouchableOpacity
                                                style={styles.removeImageButton}
                                                onPress={() => {
                                                    setUploadedImages(prev => prev.filter((_, i) => i !== index));
                                                }}
                                            >
                                                <Image source={xIcon} style={styles.removeImageIcon} />
                                            </TouchableOpacity>
                                        </View>
                                    ))}

                                    {/* 上传按钮 */}
                                    <TouchableOpacity style={styles.uploadArea} onPress={handleImageUpload}>
                                        <View style={styles.uploadIconContainer}>
                                            <Image source={xiangjiIcon} style={styles.uploadIcon} />
                                        </View>
                                        <Text style={styles.uploadText}>点击上传</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>

                            {/* 备品备件卡片 */}
                            <View style={styles.sparePartsCard}>
                                <View style={styles.sparePartsHeader}>
                                    <Text style={styles.sparePartsTitle}>备品备件</Text>
                                    <TouchableOpacity style={styles.addSparePartsButton} onPress={handleAddSpareParts}>
                                        <Image source={require('../../../../assets/jiahao.png')} style={styles.addIcon} />
                                    </TouchableOpacity>
                                </View>
                                {/* 已选择的备品备件列表（新样式） */}
                                {selectedSpareParts.length > 0 && (
                                    <View style={{ marginTop: 10 }}>
                                        {selectedSpareParts.map(item => (
                                            <View key={item.id} style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 6 }}>
                                                <Text style={{ flex: 1 }}>{item.product_name}</Text>
                                                <TouchableOpacity onPress={() => handleQuantityChange(item.id, -1)} style={{ paddingHorizontal: 8 }}>
                                                    <Text style={{ fontSize: 18 }}>-</Text>
                                                </TouchableOpacity>
                                                <Text style={{ width: 30, textAlign: 'center' }}>{item.quantity}</Text>
                                                <TouchableOpacity onPress={() => handleQuantityChange(item.id, 1)} style={{ paddingHorizontal: 8 }}>
                                                    <Text style={{ fontSize: 18 }}>+</Text>
                                                </TouchableOpacity>
                                                <TouchableOpacity onPress={() => handleRemoveSparePart(item.id)} style={{ paddingHorizontal: 8 }}>
                                                    <Text style={{ color: 'red' }}>删除</Text>
                                                </TouchableOpacity>
                                            </View>
                                        ))}
                                    </View>
                                )}
                            </View>
                            {/* 已复核显示复核意见 */}
                            {detailData.plan.state === 3 && detailData.plan.confirm_remark && (
                                <View style={{ backgroundColor: '#fff', borderRadius: 10, marginBottom: 14, padding: 12, shadowColor: '#000', shadowOpacity: 0.04, shadowRadius: 4, shadowOffset: { width: 0, height: 2 }, elevation: 2 }}>
                                    <Text style={{ fontSize: 16, fontWeight: 'bold', color: '#333', marginBottom: 8, paddingBottom: 8, borderBottomWidth: 1, borderBottomColor: '#eee' }}>复核意见</Text>
                                    <Text style={{ fontSize: 14, color: '#666', lineHeight: 20 }}>{detailData.plan.confirm_remark}</Text>
                                </View>
                            )}
                            {/* 保存/复核按钮 */}
                            {detailData.plan.state === 2 ? (
                                <TouchableOpacity style={styles.saveButton} onPress={() => setConfirmModalVisible(true)}>
                                    <Text style={styles.saveButtonText}>复核</Text>
                                </TouchableOpacity>
                            ) : (
                                <TouchableOpacity style={styles.saveButton} onPress={handleSave}>
                                    <Text style={styles.saveButtonText}>保存</Text>
                                </TouchableOpacity>
                            )}
                        </>
                    )}
                </ScrollView>
            )}

            {/* 图片全屏显示模态框 */}
            <Modal
                visible={imageModalVisible}
                transparent={true}
                animationType="fade"
                onRequestClose={() => setImageModalVisible(false)}
            >
                <View style={styles.imageModalContainer}>
                    {/* 关闭按钮 */}
                    <TouchableOpacity
                        style={styles.imagePreviewCloseBtn}
                        onPress={() => setImageModalVisible(false)}
                    >
                        <Image source={require('../../../../assets/xx.png')} style={styles.imagePreviewCloseIcon} />
                    </TouchableOpacity>
                    {/* 居中显示图片 */}
                    <Image
                        source={{ uri: selectedImage }}
                        style={styles.imagePreviewImage}
                        resizeMode="contain"
                    />
                </View>
            </Modal>

            {/* 备品备件选择模态框 */}
            <Modal visible={sparePartsModalVisible} transparent={true} animationType="slide">
                <View style={styles.sparePartsModalContainer}>
                    <View style={styles.sparePartsModalContent}>
                        {/* 右上角关闭按钮 */}
                        <TouchableOpacity style={styles.supplierCloseBtn} onPress={() => setSparePartsModalVisible(false)}>
                            <Image source={require('../../../../assets/xx.png')} style={styles.supplierCloseIcon} />
                        </TouchableOpacity>

                        {/* 模态框标题 */}
                        <View style={styles.modalHeader}>
                            <Text style={styles.modalTitle}>选择备件</Text>
                        </View>

                        {/* 搜索栏 */}
                        <View style={styles.searchContainer}>
                            <View style={styles.searchInputContainer}>
                                <Image source={require('../../../../assets/ss.png')} style={styles.searchIcon} />
                                <TextInput
                                    style={styles.searchInput}
                                    placeholder="请输入关键词搜索"
                                    placeholderTextColor="#999"
                                    value={searchKeyword}
                                    onChangeText={handleSearchInputChange}
                                />
                            </View>
                        </View>

                        {/* 备品备件列表 */}
                        <ScrollView style={styles.materialListContainer}>
                            {materialLoading ? (
                                <View style={styles.loadingContainer}>
                                    <ActivityIndicator size="large" color="#0076ff" />
                                    <Text style={styles.loadingText}>加载中...</Text>
                                </View>
                            ) : materialList.length > 0 ? (
                                materialList.map((item: any) => (
                                    <TouchableOpacity key={item.id} style={styles.materialItem} onPress={() => handleSelectSparePart(item)}>
                                        <View style={styles.materialInfo}>
                                            <Text style={styles.materialName}>{item.product_name}</Text>
                                        </View>
                                    </TouchableOpacity>
                                ))
                            ) : (
                                <View style={styles.emptyContainer}>
                                    <Text style={styles.emptyText}>
                                        暂无备品备件
                                    </Text>
                                </View>
                            )}
                        </ScrollView>
                    </View>
                </View>
            </Modal>

            {/* 复核模态框 */}
            <Modal visible={confirmModalVisible} transparent={true} animationType="slide">
                <View style={[styles.sparePartsModalContainer, { justifyContent: 'center', alignItems: 'center' }]}>
                    <View style={[styles.sparePartsModalContent, { width: '80%', height: undefined, padding: 20 }]}>
                        <Text style={{ fontSize: 18, fontWeight: 'bold', color: '#333', marginBottom: 15, textAlign: 'center' }}>复核</Text>
                        <TextInput
                            style={{ borderWidth: 1, borderColor: '#ddd', borderRadius: 8, padding: 12, fontSize: 16, minHeight: 100, marginBottom: 20 }}
                            placeholder="请输入复核备注"
                            placeholderTextColor="#999"
                            value={confirmRemark}
                            onChangeText={setConfirmRemark}
                            multiline={true}
                            numberOfLines={4}
                            textAlignVertical="top"
                        />
                        <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
                            <TouchableOpacity
                                style={{ borderWidth: 1, borderColor: '#0076ff', borderRadius: 6, paddingVertical: 8, paddingHorizontal: 16, backgroundColor: '#fff', marginRight: 10 }}
                                onPress={() => { setConfirmModalVisible(false); setConfirmRemark(''); }}
                            >
                                <Text style={{ color: '#0076ff', fontSize: 16 }}>取消</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={{ backgroundColor: '#0076ff', borderRadius: 6, paddingVertical: 8, paddingHorizontal: 16 }}
                                onPress={handleConfirm}
                            >
                                <Text style={{ color: '#fff', fontSize: 16, fontWeight: 'bold' }}>确认</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    loadingText: {
        marginTop: 10,
        fontSize: 16,
        color: '#666',
    },
    errorContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    errorText: {
        fontSize: 16,
        color: '#999',
    },
    // New styles for the card layout
    content: {
        padding: 10,
        backgroundColor: '#f5f5f5',
    },
    card: {
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 14,
        padding: 12,
        shadowColor: '#000',
        shadowOpacity: 0.4,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
    },
    cardHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 8,
    },
    deviceInfo: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
    },
    imageContainer: {
        width: 50,
        height: 50,
        borderRadius: 6,
        backgroundColor: '#eee',
        marginRight: 12,
    },
    deviceImg: {
        width: '100%',
        height: '100%',
    },
    deviceNum: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#222',
    },
    statusButton: {
        backgroundColor: '#fff',
        borderRadius: 4,
        paddingVertical: 6,
        paddingHorizontal: 12,
        borderWidth: 1,
        borderColor: '#ff4444',
    },
    statusText: {
        fontSize: 12,
        color: '#ff4444',
        fontWeight: 'bold',
    },
    cardDetails: {
        marginTop: 8,
        backgroundColor: '#f8f8f8',
        borderRadius: 8,
        padding: 12,
        paddingHorizontal: 15,
    },
    detailRowGroup: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 6,
        paddingHorizontal: 0,
    },
    detailItemVertical: {
        flex: 0,
        width: '24%',
    },
    detailItemVertical1: {
        flex: 0,
        width: '20%',
    },
    detailLabel: {
        fontSize: 13,
        color: '#666',
        marginBottom: 4,
    },
    detailValue: {
        fontSize: 12,
        color: '#333',
        textAlign: 'left',
    },
    planNumberContainer: {
        marginTop: 8,
        backgroundColor: '#f8f8f8',
        borderRadius: 8,
        padding: 12,
        paddingHorizontal: 15,
    },
    spotItemCard: {
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 14,
        padding: 12,
        shadowColor: '#000',
        shadowOpacity: 0.4,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    spotItemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
    },
    spotItemText: {
        fontSize: 16,
        color: '#333',
        fontWeight: '500',
    },
    requiredMark: {
        fontSize: 16,
        color: '#ff4444',
        marginLeft: 4,
    },
    spotItemRight: {
        alignItems: 'flex-end',
    },
    spotItemStatus: {
        fontSize: 14,
        color: '#666',
    },
    checkCategoryCard: {
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 14,
        padding: 12,
        shadowColor: '#000',
        shadowOpacity: 0.4,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
    },
    checkCategoryTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 10,
        paddingBottom: 8,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    checkItemRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 8,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    checkItemName: {
        fontSize: 14,
        color: '#333',
        flex: 1,
        marginRight: 10,
    },
    uploadCard: {
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 14,
        padding: 12,
        shadowColor: '#000',
        shadowOpacity: 0.4,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
    },
    uploadTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 10,
        paddingBottom: 8,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    uploadArea: {
        width: 70,
        height: 70,
        backgroundColor: '#f5f5f5',
        borderRadius: 8,
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#e0e0e0',
        borderStyle: 'dashed',
    },
    imagesRow: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 10,
    },
    imageItem: {
        position: 'relative',
        marginRight: 10,
        marginBottom: 10,
    },
    uploadIconContainer: {
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 8,
    },
    uploadIcon: {
        width: 32,
        height: 32,
        tintColor: '#999',
    },
    uploadText: {
        fontSize: 12,
        color: '#999',
    },
    uploadedImage: {
        width: 70,
        height: 70,
        borderRadius: 8,
    },
    removeImageButton: {
        position: 'absolute',
        top: 0,
        right: 0,
        width: 17,
        height: 17,
        justifyContent: 'center',
        alignItems: 'center',
        // backgroundColor: '#ff4444',
        borderRadius: 8,
    },
    removeImageIcon: {
        width: 16,
        height: 16,
        // tintColor: '#fff',
    },
    saveButton: {
        backgroundColor: '#0076ff',
        borderRadius: 8,
        paddingVertical: 12,
        paddingHorizontal: 20,
        marginBottom: 10,
        alignItems: 'center',
        justifyContent: 'center',
    },
    saveButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    imageModalContainer: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.9)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    imagePreviewCloseBtn: {
        position: 'absolute',
        top: 40,
        right: 20,
        zIndex: 10,
        width: 40,
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
    },
    imagePreviewCloseIcon: {
        width: 30,
        height: 30,
        resizeMode: 'contain',
    },
    imagePreviewImage: {
        width: '90%',
        height: '90%',
        borderRadius: 10,
    },
    sparePartsCard: {
        backgroundColor: '#fff',
        borderRadius: 10,
        marginBottom: 14,
        padding: 12,
        shadowColor: '#000',
        shadowOpacity: 0.4,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 2,
    },
    sparePartsHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        // marginBottom: 8,
    },
    sparePartsTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
    },
    addSparePartsButton: {
        padding: 5,
    },
    addIcon: {
        width: 24,
        height: 24,
    },
    sparePartsModalContainer: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'flex-end',
    },
    sparePartsModalContent: {
        backgroundColor: '#fff',
        // borderTopLeftRadius: 10,
        // borderTopRightRadius: 10,
        width: '100%',
        height: '80%',
        padding: 20,
    },
    modalHeader: {
        width: '100%',
        alignItems: 'center',
        marginBottom: 20,
    },
    modalTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
    },
    searchContainer: {
        width: '100%',
        backgroundColor: '#f0f0f0',
        borderRadius: 8,
        paddingHorizontal: 10,
        marginBottom: 20,
    },
    searchInputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        width: '100%',
        paddingVertical: 0,
        height: 40,
    },
    searchIcon: {
        width: 20,
        height: 20,
        marginRight: 10,
    },
    searchInput: {
        flex: 1,
        fontSize: 14,
        color: '#333',
        height: 40,
        paddingVertical: 0,
    },
    materialListContainer: {
        flex: 1,
        width: '100%',
        marginTop: 10,
    },
    materialItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    materialImageContainer: {
        width: 50,
        height: 50,
        borderRadius: 6,
        backgroundColor: '#eee',
        marginRight: 15,
        justifyContent: 'center',
        alignItems: 'center',
    },
    materialImage: {
        width: '100%',
        height: '100%',
        borderRadius: 6,
    },
    materialImagePlaceholder: {
        width: '100%',
        height: '100%',
        backgroundColor: '#eee',
        borderRadius: 6,
    },
    materialInfo: {
        flex: 1,
        marginRight: 10,
    },
    materialName: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#333',
    },
    materialModel: {
        fontSize: 12,
        color: '#666',
    },
    materialStock: {
        alignItems: 'flex-end',
    },
    stockText: {
        fontSize: 14,
        fontWeight: 'bold',
        color: '#ff4444',
    },
    stockUnit: {
        fontSize: 12,
        color: '#666',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 20,
    },
    emptyText: {
        fontSize: 14,
        color: '#999',
    },
    cancelButton: {
        backgroundColor: '#f0f0f0',
        borderRadius: 8,
        paddingVertical: 10,
        paddingHorizontal: 20,
        marginTop: 15,
        width: '100%',
        alignItems: 'center',
    },
    cancelButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
    },
    selectedSparePartsList: {
        marginTop: 10,
    },
    selectedSparePartItem: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 8,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    selectedSparePartInfo: {
        flex: 1,
    },
    selectedSparePartName: {
        fontSize: 14,
        color: '#333',
        fontWeight: '500',
    },
    quantityControl: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    quantityButton: {
        width: 30,
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: 5,
        backgroundColor: 'transparent', // 移除蓝色背景
        borderRadius: 0, // 移除圆角
    },
    quantityButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    quantityText: {
        fontSize: 16,
        // color: '#333',
        // fontWeight: 'bold',
        // marginHorizontal: 5,
        minWidth: 20,
        textAlign: 'center',
        lineHeight: 30,
    },
    supplierCloseBtn: {
        position: 'absolute',
        top: 10,
        right: 10,
        zIndex: 1,
    },
    supplierCloseIcon: {
        width: 24,
        height: 24,
    },
});

export default DeviceMaintainDetail; 